package exchange.direct;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class Consumer1 {

	private static final String EXCHANGE_NAME = "logs1";
	
	public static void main(String[] args) {
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost("localhost");
			Connection connect = factory.newConnection();
			Channel channel = connect.createChannel();
			channel.exchangeDeclare(EXCHANGE_NAME,"direct");
//			String queueName = channel.queueDeclare().getQueue();
			String queueName = "aaaa";
			//durable： 是否持久化, 队列的声明默认是存放到内存中的，如果rabbitmq重启会丢失，
//			如果想重启之后还存在就要使队列持久化，保存到Erlang自带的Mnesia数据库中，
//			当rabbitmq重启之后会读取该数据库
//			exclusive：是否排外的，有两个作用，一：当连接关闭时connection.close()该队列是否会自动删除；
//			二：该队列是否是私有的private，
//			如果不是排外的，可以使用两个消费者都访问同一个队列，没有任何问题，如果是排外的，
//			会对当前队列加锁，其他通道channel是不能访问的，
//			如果强制访问会报异常：com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=405, 
//			reply-text=RESOURCE_LOCKED - cannot obtain exclusive access to locked queue 'queue_name' in vhost '/', class-id=50, method-id=20)
//			一般等于true的话用于一个队列只能有一个消费者来消费的场景
			channel.queueDeclare(queueName, true,false,false,null);
			channel.queueBind(queueName,EXCHANGE_NAME,"abc");
			
			Consumer consumer = new DefaultConsumer(channel) {

				@Override
				public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties,
						byte[] body) throws IOException {
//					super.handleDelivery(consumerTag, envelope, properties, body);
					String message = new String(body,"utf-8");
					 System.out.println(" consumer1 Received '" + message + "'");
				}
				
			};
//			channel.basicConsume(queueName,true,consumer);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
		}
	}
}
